import Koa from 'koa'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import koaCors from 'koa-cors'
import { sync } from './db/index.js'
import { User } from './model/User.js'
import { Op } from 'sequelize'

const app = new Koa()
const router = new Router()
sync()

app.use(koaCors())
app.use(bodyParser())

router.get("/users", async (ctx) => {
    let keyword = ctx.query.keyword
    console.log(keyword);
    let users;
    if (keyword) {
        users = await User.findAll({
            where: {
                [Op.or]: {
                    uname: {
                        [Op.like]: `%${keyword}%`
                    },
                    uage: {
                        [Op.like]: `%${keyword}%`
                    }
                }
            }
        })
    } else {
        users = await User.findAll()
    }
    ctx.body = users;
})

router.get("/user/:id", async (ctx) => {
    let id = ctx.params.id
    let user = await User.findByPk(id)
    ctx.body = user;
})

router.delete("/user/:id", async (ctx) => {
    let id = ctx.params.id
    await User.destroy({ where: { id } })
    ctx.body = "删除成功";
})

router.post("/user", async (ctx) => {
    let obj = ctx.request.body
    console.log(obj);

    await User.create(obj)
    ctx.body = "新增成功";
})

router.put("/user/:id", async (ctx) => {
    let id = ctx.params.id
    let obj = ctx.request.body
    await User.update(obj, { where: { id } })
    ctx.body = "修改成功";
})

app.use(router.routes())
app.listen(3000)